package com.lfg.leetcode.leetcode1000;


public class No1219getMaximumGold {
    public static void main(String[] args) {
        int[][] properties = {{1, 6, 1}, {5, 8, 7}, {1, 9, 1}};
        System.out.println(getMaximumGold(properties));
    }

    public static int getMaximumGold(int[][] grid) {
        int ret = 0;
        int[][] nums = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                ret = Math.max(ret, dfs(nums, grid, i, j, 0));
            }
        }

        return ret;
    }

    public static int dfs(int[][] nums, int[][] grid, int i, int j, int cnt) {
        int ret = 0;

        if (i >= grid.length) {
            return cnt;
        }
        if (j >= grid[0].length) {
            return cnt;
        }


        if (grid[i][j] == 0) {
            return cnt;
        }
        if (nums[i][j] == 1) {
            return cnt;
        }
        nums[i][j] = 1;

        cnt += grid[i][j];
        if (i < grid.length - 1) {
            ret = Math.max(ret, dfs(nums, grid, i + 1, j, cnt));
        }

        if (j < grid[0].length - 1) {
            ret = Math.max(ret, dfs(nums, grid, i, j + 1, cnt));
        }
        if (i > 0) {
            ret = Math.max(ret, dfs(nums, grid, i - 1, j, cnt));
        }
        if (j > 0) {
            ret = Math.max(ret, dfs(nums, grid, i, j - 1, cnt));
        }
        nums[i][j] = 0;
        return ret;
    }
}

